import myAxios from "axios"
import { Local } from "../common"
import { TOKEN } from "./localConstant"
import { messageTip } from "../components/JS"
import NProgress from 'nprogress'

let axios = myAxios.create({
    timeout: 10000,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
})

let errIndex = 0
axios.interceptors.request.use(config => {
    NProgress.start() /* 开始 */
    if(errIndex >= 5) {
        messageTip({
            content: "请求错误，请重试..."
        })
        return Promise.reject({
            status: 400,
            msg: "请求错误，请重试..."
        })
    }
    if(!config.url.includes("/login")) {
        const { msg } = Local.get(TOKEN)
        if(!msg) {
            errIndex++
            location.hash = "/login"
        }
        config.headers["Authorization"] = msg
    }
    // console.log("config：：", config)
    return config;
}, (err) => {
    console.error("请求err:: ", err.message)
    return Promise.reject(err.message)
})

axios.interceptors.response.use(res => {
    // console.log("data：：", res.data)
    setTimeout(() => {
    switch (res.data.status) {
        case 200000:
            // messageTip({content: "验证成功"})
            break;
        case 200201:
            messageTip({content: "登录成功"})
            break;
        case 200202:
            messageTip({content: "退出成功"})
            break;
        case 200203:
            const state = Boolean(Number(res.data.data.userState))
            messageTip({
                content: "用户状态修改成功，该用户状态为 -- " + state})
            break;
        case 200205:
            messageTip({content: "添加成功"})
            break;
        case 200401:
            messageTip({content: "用户名或密码错误，请重新登录"})
            break;
        case 400400:
            let errMsg = res.data.errCode
            if(errMsg === "jwt expired") { /* token 过期 */
                messageTip({content: "用户信息验证过期，请重新登录"})
                Local.remove(TOKEN)
                location.hash = "/login"
            }
        case 400401:
            messageTip({content: "用户信息验证丢失，请重新登录"})
            Local.remove(TOKEN)
            break;
        case 400402:
            messageTip({content: res.data.errCode})
            break;
    }
    NProgress.done() /* 结束 */
}, 120)
    return res;
}, err => {
    let statusCode = err.message.match(/(\d+)*$/g)[0]
    console.error("响应err:: ", err.message)
    if(err.message.includes('timeout')) {
        messageTip({content: '响应超时，请刷新重试'})
    }
    switch (statusCode) {
        case "500":
            messageTip({content: "服务器连接失败"})
            Local.remove(TOKEN)
            return;
        default:
            return Promise.reject(err.message)
    }
})

export default axios;